<template>
  <div id="job">
    <div class="bodyContent">
      <div class="contentDiv">
        <vxe-toolbar perfect>
          <template #buttons>
            <vxe-form :data="queryParams" ref="queryForm" :inline="true">
              <vxe-form-item title="主记录ID" clearable>
                <vxe-input v-model="queryParams.operatorId" placeholder="请输入业务ID" clearable style="width: 200px" />
              </vxe-form-item>
              <vxe-form-item title="关键字查询" clearable>
                <vxe-input v-model="queryParams.keywords" placeholder="请输入关键字" clearable style="width: 200px" />
              </vxe-form-item>
              <vxe-form-item title="日期" clearable>
                <vxe-input type="date" v-model="queryParams.startTime"></vxe-input> - <vxe-input type="date" v-model="queryParams.endTime"></vxe-input>
              </vxe-form-item>
              <vxe-form-item title="业务模块">
                <vxe-select ref="refType" v-model="queryParams.businessName" placeholder="请选择业务模块" style="width:100%;">
                  <vxe-option v-for="intf in businessList" :key="intf.value" :label="intf.name" :value="intf.value"></vxe-option>
                </vxe-select>
              </vxe-form-item>
              <vxe-form-item title="状态标识">
                <vxe-select ref="refType" v-model="queryParams.flag" placeholder="请选择业务模块" style="width:100%;">
                  <vxe-option v-for="intf in statusList" :key="intf.value" :label="intf.name" :value="intf.value"></vxe-option>
                </vxe-select>
              </vxe-form-item>
              <vxe-form-item>
                <vxe-button content="查询" type="text" class="button-blue" @click="handleQuery" icon="vxe-icon-search"></vxe-button>
                <vxe-button content="重置" type="text" class="button-blue" @click="resetQuery" icon="vxe-icon-refresh"></vxe-button>
              </vxe-form-item>
            </vxe-form>
          </template>
        </vxe-toolbar>

        <div class="tableBox">
          <vxe-table ref="tableRef" :data="jobList" class="mytable-scrollbar" border="inner" align="left" height="auto" :loading="tableLoading" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
            <vxe-column type="seq" width="30" title="#"></vxe-column>
            <vxe-column title="业务id" field="operatorId" />
            <vxe-column title="操作时间" field="operateTime" />
            <vxe-column title="操作人" field="userName" />
            <vxe-column title="业务模块" field="businessName" />
            <vxe-column title="耗时(ms)" field="takeTime" width="100" />
            <vxe-column title="入参" field="reqParam" :show-overflow-tooltip="true" />
            <vxe-column title="出参" field="repParam" :show-overflow-tooltip="true" />
            <vxe-column title="成功标识" field="flag" width="80">
              <template #default="{ row }">
                <el-tag v-if="row.flag=='1'" type="success">成功</el-tag>
                <el-tag v-else type="error">失败</el-tag>
              </template>
            </vxe-column>
            <vxe-column title="操作" align="center">
              <template #default="{ row }">
                <vxe-button type="text" status="primary" icon="vxe-icon-ellipsis-h" circle @click="handleUpdate(row)"> </vxe-button>
                <!-- <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle @click="handleDelete(row)"> </vxe-button> -->
              </template>
            </vxe-column>
          </vxe-table>
          <vxe-pager align="left" style="margin-top: 2px" size="mini" min-height="auto" :current-page.sync="page.currentPage" :page-size.sync="page.pageSize" :total="page.totalResult" :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']" @page-change="handleSizeChange($event)"></vxe-pager>
        </div>
      </div>
      <vxe-modal class-name="animation-slide-right" v-model="moduleDialog1" title="日志详情" width="50vw" height="80vh" show-zoom resize>
        <div>
          <el-descriptions :column="2" border>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <el-icon :style="iconStyle">
                    <Location />
                  </el-icon>
                  请求地址
                </div>
              </template>
              {{ formDetails.requestUrl }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <el-icon :style="iconStyle">
                    <AlarmClock />
                  </el-icon>
                  操作时间
                </div>
              </template>
              {{ formDetails.operateTime }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <el-icon :style="iconStyle">
                    <Timer />
                  </el-icon>
                  消耗时间
                </div>
              </template>
              <el-tag size="small">{{ formDetails.takeTime }}/毫秒</el-tag>
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <el-icon :style="iconStyle">
                    <Refresh />
                  </el-icon>
                  操作状态
                </div>
              </template>
              <el-tag size="small">
                <div v-if="formDetails.flag === '0'">正常</div>
                <div v-else-if="formDetails.flag === '1'">失败</div>
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <el-icon :style="iconStyle">
                    <ChatSquare />
                  </el-icon>
                  操作內容
                </div>
              </template>
              {{ formDetails.content }}
            </el-descriptions-item>
          </el-descriptions>
          <el-descriptions class="buttomDescriptions" :column="1" style="width: 100%" append-to-body border>
            <!-- 这里是您的描述内容 -->

            <el-descriptions-item>
              <template #label>
                <div class="cell-item1">
                  <el-icon :style="iconStyle">
                    <ChromeFilled />
                  </el-icon>
                  操作方法
                </div>
              </template>
              <el-scrollbar>
                <div class="selectable">
                  {{ formDetails.method }}
                </div>
              </el-scrollbar>
            </el-descriptions-item>

            <el-descriptions-item>
              <template #label>
                <div class="cell-item1">
                  <el-icon :style="iconStyle">
                    <Tickets />
                  </el-icon>
                  请求参数
                </div>
              </template>
              <el-scrollbar>
                <div class="selectable">{{ formDetails.reqParam }}</div>
              </el-scrollbar>
            </el-descriptions-item>

            <el-descriptions-item>
              <template #label>
                <div class="cell-item1">
                  <el-icon :style="iconStyle">
                    <Tickets />
                  </el-icon>
                  返回参数
                </div>
              </template>
              <el-scrollbar>
                <div class="selectable">{{ formDetails.repParam }}</div>
              </el-scrollbar>
            </el-descriptions-item>
          </el-descriptions>
          <div style="text-align:right;margin:5px;">
            <vxe-button content="重新发送" type="text" class="button-red" @click="reCall"></vxe-button>
          </div>
        </div>
      </vxe-modal>
    </div>
  </div>
</template>

<script setup lang="ts">
// 引入组件区==========
import { getCurrentInstance, onMounted, reactive, ref, watch, computed } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue'; //面包屑
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { CaretRight, View } from '@element-plus/icons-vue';
import { IsEmpty, formatDateTime } from '@/utils/common.ts';
import { Splitpanes, Pane } from 'splitpanes';
import { VXETable } from 'vxe-table';
import InterfaceMethValue from '@/views/interface/InterfaceMethValue.vue';
import moment from 'moment';

// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();

const val1 = ref(); //选择任务名
const val2 = ref(); //选择任务名

let tableLoading = ref(true); //表格加载状态
let formDetails = reactive({});
const size = ref('');

const PageSizeList = [10, 50, 100, 200, 500];
let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});

let ids: any = reactive([]); //选中数组
let groupList = reactive([]);
let statusList = reactive([
  {
    value: '',
    name: '全部'
  },
  {
    value: '0',
    name: '失败'
  },
  {
    value: '1',
    name: '成功'
  }
]);
let single = ref(true); //非单个禁用
let multiple = ref(true); //非多个禁用
let showSearch = ref(true); //显示搜索条件
// 定时任务表格数据
let jobList = reactive([]);
let businessList = reactive([]);
let title = ref(''); //弹出层标题
let open = ref(false); //是否显示弹出层
let openView = ref(false); //是否显示详细弹出层
let expression: UnwrapRef<string> = ref(''); //传入的表达式
let moduleDialog1 = ref(false);
let refInterfaceMethValue = ref('');
let queryParams = reactive({
  operatorId: '',
  keywords: '',
  flag: '',
  businessName: '',
  startTime: moment().format('YYYY-MM-DD'),
  endTime: moment().format('YYYY-MM-DD')
}); //传入的表达式
// 表单参数
let form = reactive({
  id: '',
  title: '',
  jobGroup: '',
  invokeTarget: '',
  cronExpression: '',
  misfirePolicy: 1,
  concurrent: 1,
  status: 0,
  systemId: '',
  moduleId: '',
  requestType: '',
  url: ''
});

let showLoading = ref(false); //刷新+表格加载
let jobTableList = reactive([]);
let props = defineProps({
  systemId: String,
  moduleId: String,
  moduleSystemName: String
}) as any;
const iconStyle = computed(() => {
  const marginMap = {
    large: '8px',
    default: '6px',
    small: '4px'
  };
  return {
    marginRight: marginMap[size.value] || marginMap.default
  };
});
watch(
  () => props.systemId,
  (n, o) => {
    getList();
  },
  {
    deep: true,
    immediate: true
  }
);
watch(
  () => props.moduleId,
  (newval, oldvbal) => {
    getList();
  },
  {
    deep: true
  }
);

let searchValue = ref('');
let formRef: any = ref(null); //弹框新增
let formRef2: any = ref(null); //弹框编辑 任务详细
let selectMainItemRow: any = reactive({});
const jobVsMainItemList = reactive([]);
const mainItemAllList = reactive([]);

onMounted(() => {
  getLogType();
});

/** 查询定时任务列表 */
function getList() {
  jobList.length = 0;
  tableLoading.value = true;
  const url = '/api/sys/SysInterfaceFunction/findSysInterfaceModuleLog';
  proxy.$http
    .get(url, {
      params: {
        operatorId: queryParams.operatorId,
        systemId: props.systemId,
        moduleId: props.moduleId,
        pageIndex: page.currentPage,
        pageSize: page.pageSize,
        startTime: queryParams.startTime + ' 00:00:00',
        endTime: queryParams.endTime + ' 23:59:59',
        keywords: queryParams.keywords,
        flag: queryParams.flag,
        businessName: queryParams.businessName
      }
    })
    .then((res: any) => {
      jobList.length = 0;
      jobList.push(...res.data.records);
      page.totalResult = res.data.total;
      tableLoading.value = false;
    })
    .catch((err) => {
      tableLoading.value = false;
      VxeMessage(err, VxeNotifyType.error);
    });
}

function getLogType() {
  businessList.length = 0;
  const url = '/api/sys/SysInterfaceFunction/findSysInterfaceModuleLogType';
  proxy.$http
    .get(url)
    .then((res: any) => {
      businessList.push(...res.data);
    })
    .catch((err) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}
function handleUpdate(row) {
  moduleDialog1.value = true;
  Object.assign(formDetails, row);
  console.log(formDetails);
}

// 表单重置
function reset() {
  let $formEl = formRef.value as any;
  let $formEl2 = formRef2.value as any;
  if ($formEl) {
    $formEl.resetFields();
  }

  if ($formEl2) {
    $formEl2.resetFields();
  }

  form.id = '';
  form.jobName = '';
  form.jobGroup = '';
  form.invokeTarget = '';
  form.cronExpression = '';
  form.requestType = '';
  form.url = '';
  form.misfirePolicy = 1;
  form.concurrent = 1;
  form.status = 0;
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

async function reCall() {
  const type = await VXETable.modal.confirm('确定要重发接口吗？');
  if (type === 'confirm') {
    const url = '/api/sys/SysInterfaceFunction/reCallInterface';
    proxy.$http.post(url, formDetails).then((res: any) => {
      if (res.status.code === 1) {
        VxeMessage('重发成功', VxeNotifyType.success);
        moduleDialog1.value = false;
        getList();
      } else {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      }
    });
  }
}

//点击每页数量
function handleSizeChange({ type, currentPage, pageSize }) {
  if (type === 'size') {
    page.currentPage = 1;
  } else {
    page.currentPage = currentPage;
  }
  page.pageSize = pageSize;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.operatorId = '';
  queryParams.keywords = '';
  queryParams.flag = '';
  queryParams.businessName = '';
  queryParams.startTime = moment().format('YYYY-MM-DD');
  queryParams.endTime = moment().format('YYYY-MM-DD');
  handleQuery();
}
</script>
<style lang="scss" scoped>
#job {
  width: 100%;
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);

    .contentDiv {
      height: 100%;
      background-color: $base-white;

      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 5px 5px 0;
      }

      .vxe-form {
        :deep(.vxe-form--item) {
          margin-right: 10px;
        }
      }

      .tableBox {
        height: calc(100% - 40px);
      }
    }
  }

  .leftTable {
    height: calc(100% - 30px);
  }

  :deep(.el-tabs) {
    height: 100%;
  }

  :deep(.el-tabs__content) {
    padding: 0;
    height: calc(100% - 40px);

    .el-tab-pane {
      height: 100%;
    }
  }
}
</style>

<style lang="scss">
.addEditTaskDialog {
  .el-form {
    .el-form-item {
      margin-bottom: 20px;
    }
  }

  .dialogFooter {
    float: right;

    .el-button {
      float: right;
      margin-left: 10px;
    }
  }
}

.taskLogDetailDialog {
  height: 300px;

  .el-dialog__body {
    padding: 10px;

    .dialogFooter {
      margin: 10px;

      .el-button {
        float: right;
      }
    }
  }
}
</style>
